using System;
using System.Drawing;
using System.Windows.Forms;
using Habanero.Faces.Base;
using Habanero.Faces.Win;
using DockStyle=Habanero.Faces.Base.DockStyle;

namespace FireStarterModeller.UI
{
    //TODO Eric 31 Aug 2009: move this and the mapper back into Habanero
    public class DirectorySelectorControl : UserControlWin, IControlManager
    {
        private readonly IButton _fileSelectorButton;
        private readonly ITextBox _fileSelectorTextBox;
        private readonly IPanel _panel;
        private FolderBrowserDialog _folderBrowserDialog;

        public DirectorySelectorControl()
        {
            IControlFactory controlFactory = GlobalUIRegistry.ControlFactory;

            _panel = controlFactory.CreatePanel();

            this.Height = 20;

            _fileSelectorTextBox = controlFactory.CreateTextBox();
            //_fileSelectorTextBox.Width = 300;
            _fileSelectorTextBox.Dock = DockStyle.Left;

            _fileSelectorButton = controlFactory.CreateButton("...", FileSelector_Click);
            _fileSelectorButton.Height = 22;
            _fileSelectorButton.Width = 25;
            _fileSelectorButton.Dock = DockStyle.Right;
            _fileSelectorButton.MaximumSize = new Size(25, 22);
            _fileSelectorButton.MinimumSize = new Size(25, 22);

            FlowLayoutManager flowLayoutManager = new FlowLayoutManager(_panel, controlFactory);
            flowLayoutManager.AddControl(_fileSelectorTextBox);
            flowLayoutManager.AddControl(_fileSelectorButton);

            BorderLayoutManager borderLayoutManager = controlFactory.CreateBorderLayoutManager(this);
            borderLayoutManager.AddControl(_panel, BorderLayoutManager.Position.Centre);

            this.Height = _fileSelectorTextBox.Height;
            this.Width = _fileSelectorTextBox.Width + _fileSelectorButton.Width;
            this.Resize += delegate {_fileSelectorTextBox.Width = this.Width - _fileSelectorButton.Width;};
        }

        protected virtual void FileSelector_Click(object sender, EventArgs e)
        {
            _folderBrowserDialog = new FolderBrowserDialog();
            if (!String.IsNullOrEmpty(_fileSelectorTextBox.Text))
                _folderBrowserDialog.SelectedPath = _fileSelectorTextBox.Text;
            _folderBrowserDialog.ShowDialog();
            string path = _folderBrowserDialog.SelectedPath;
            this.FileSelectorTextBox.Text = path;
        }

        public ITextBox FileSelectorTextBox
        {
            get { return _fileSelectorTextBox; }
        }

        public IButton FileSelectorButton
        {
            get { return _fileSelectorButton; }
        }

        public IControlHabanero Control
        {
            get { return this; }
        }
    }

}